<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/22
 * Time: 16:59
 */

namespace app\controllers;

use app\models\Announce;
use yii;

class AnnounceController extends ApiBaseController
{

    public function actionList()
    {
        $where = [];
        $page = yii::$app->request->get('page', 1);
        $pageSize = yii::$app->request->get('pageSize', 10);
        $model = new Announce();
        $list = $model->all($where, ($page - 1) * $pageSize, $pageSize);
        $total = $model->size($where);
        return \json_encode(['list' => $list, 'total' => $total]);
    }

    public function actionAdd()
    {
        $data = [];
        $data['staff'] = $this->user['job_number'];
        $data['time'] = time();
        $data['title'] = yii::$app->request->post('title', '');
        $data['file_path'] = yii::$app->request->post('filePath', '');
        $data['detail'] = yii::$app->request->post('detail', '');
        if (!$data['title']) {
            return \json_encode(['code' => 0, 'msg' => '参数错误']);
        }
        $model = new Announce();
        $re = $model->insert($data);
        $output = $re ? ['code' => 1, 'msg' => '添加成功'] : ['code' => 0, 'msg' => '添加失败,请重试'];
        return \json_encode($output);
    }

    public function actionUpdate()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }
        $id = yii::$app->request->post('id', 0);
        $data = yii::$app->request->post();
        if (!is_numeric($id) || $id <= 0) {
            return \json_encode(['code' => 0, 'msg' => '参数错误']);
        }

        $model = new Announce();
        $re = $model->save($data, ['id' => $id]);
        $output = $re ? ['code' => 1, 'msg' => '修改成功'] : ['code' => 0, 'msg' => '修改失败,请重试'];
        return \json_encode($output);
    }
}